package logic

import (
	"classtype/global/model"
	"context"

	"classtype/classtype"
	"classtype/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassTypeIndexLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewClassTypeIndexLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassTypeIndexLogic {
	return &ClassTypeIndexLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ClassTypeIndexLogic) ClassTypeIndex(in *classtype.ClassTypeIndexRequest) (*classtype.ClassTypeIndexResponse, error) {
	// todo: add your logic here and delete this line
	var classTypes []model.ClassTypes
	if err := model.DB.Model(&model.ClassTypes{}).Order("sort desc").Order("created_at desc").Where("name like ?", "%"+in.Name+"%").Find(&classTypes).Error; err != nil {
		return nil, err
	}
	var ClsMap = make(map[int32][]model.ClassTypes)
	for _, classType := range classTypes {
		ClsMap[classType.ParentId] = append(ClsMap[classType.ParentId], classType)
	}
	tree := model.CreateTree(ClsMap[0], ClsMap)
	return &classtype.ClassTypeIndexResponse{
		CliClassTypeTree: tree,
	}, nil
}
